package org.dtrd.modules.shop.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.dtrd.common.api.vo.Result;
import org.dtrd.common.util.CommonUtils;
import org.dtrd.common.util.RedisUtil;
import org.dtrd.common.util.RestUtil;
import org.dtrd.common.util.oss.OssBootUtil;
import org.dtrd.modules.oss.entity.OSSFile;
import org.dtrd.modules.oss.mapper.OSSFileMapper;
import org.dtrd.modules.oss.service.IOSSFileService;
import org.dtrd.modules.shop.service.IKingdeeService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Lazy;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.multipart.MultipartFile;


import javax.annotation.Resource;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;

@Slf4j
@DS("multi-datasource1")
@Service
public class KingdeeServiceImpl implements IKingdeeService {

	@Resource
	@Lazy
	private RedisUtil redisUtil;

	@Value("${dtrd.kingdee.domain}")
	private String apiDomain;

	@Value("${dtrd.kingdee.groupName}")
	private String groupName;

	@Value("${dtrd.kingdee.accountId}")
	private String accountId;

	@Value("${dtrd.kingdee.username}")
	private String username;

	@Value("${dtrd.kingdee.password}")
	private String password;

	@Value("${dtrd.kingdee.client_id}")
	private String clientId;

	@Value("${dtrd.kingdee.client_secret}")
	private String clientSecret;

	private String getAccessToken() {
		String token;
		if (redisUtil.hasKey("KingdeeAccessToken")) {
			log.info("非第一次调用，读取redis");
			token = redisUtil.get("KingdeeAccessToken").toString();
		} else {
			log.info("第一次调用，将token存入redis");
			String httpURL = apiDomain + "/auth/user/access_token";
			JSONObject request = new JSONObject();
			request.put("username", username);
			request.put("password", password);
			request.put("client_id", clientId);
			request.put("client_secret", clientSecret);
			log.info("token url params--groupName：" + groupName);
			log.info("token url params--username：" + username);
			log.info("token url params：" + request);
			ResponseEntity<JSONObject> response = RestUtil.request(httpURL, HttpMethod.GET, null, request, null, JSONObject.class);
			// String responseBody = response.getBody();
			log.info("token responseBody：" + response);
			JSONObject data = response.getBody().getJSONObject("data");
			log.info("token responseBody data：" + data);
			if (!data.get("access_token").toString().equals("")) {
				token = data.get("access_token").toString();
				redisUtil.set("KingdeeAccessToken", token, 3600 * 24 * 7);
			} else {
				log.info("获取金蝶Token失败");
				token = "";
			}
		}
		return "?access_token=" + token;
	}


	@Override
	public JSONObject queryKingdeeApi(String url, JSONObject request) throws UnsupportedEncodingException {
//		try {

			HttpHeaders headers = new HttpHeaders();
			headers.set("Content-Type", "Application/Json;charset=utf-8");
			headers.set("groupName", groupName);
			headers.set("accountId", accountId);
			// 发送请求
			String httpURL = URLDecoder.decode(apiDomain + url + this.getAccessToken(), "UTF-8");
			ResponseEntity<String> response = RestUtil.request(httpURL, HttpMethod.POST, headers, null, request, String.class);

			String responseBody = response.getBody();
			JSONObject json = JSONObject.parseObject(responseBody);
			return json;

			// 封装返回结果
//			Result<Object> result = new Result<>();
//			int statusCode = response.getStatusCodeValue();
//			result.setCode(statusCode);
//			result.setSuccess(statusCode == 200);
//			String responseBody = response.getBody();
//			log.info("responseBody======" + responseBody);
//			try {
//				// 尝试将返回结果转为JSON
//				JSONObject json = JSONObject.parseObject(responseBody);
//				Object data = json.get("data");
//				result.setResult(data);
//			} catch (Exception e) {
//				log.info("解析失败了");
//				// 转成JSON失败，直接返回原始数据
//				result.setResult(responseBody);
//			}
//			return result;
//		} catch (Exception e) {
//			log.info("error");
//			return Result.error(e.getMessage());
//		}
	}

	@Override
	public Result<?> returnRes(JSONObject object) {
		Result<Object> result = new Result<>();

		boolean success = object.getBoolean("success");

		if (success) {
			result.setCode(200);
			result.setSuccess(true);
			JSONObject data = object.getJSONObject("data");
			result.setResult(data);
		} else {
			result.setCode(500);
			result.setSuccess(false);
			result.setResult(object);
		}

		return result;
	}

}
